//
//  ILDailySelectTableViewController.m
//  ILife
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILDailySelectTableViewController.h"
#import <AFNetworking.h>
#import "ILDailySelectModel.h"
#import "ILDailySelectTableViewCell.h"
#import <MJRefresh.h>
#import "ILDailySelectDetailViewController.h"
#import "FMDatabase.h"



@interface ILDailySelectTableViewController ()

@property(nonatomic,strong)NSMutableArray *dataArr;

@property(nonatomic,strong)NSMutableArray *dataArray;


@property(nonatomic,assign)NSInteger day;



@property(nonatomic,strong)FMDatabase *dataBase;//数据库

@end

@implementation ILDailySelectTableViewController

-(NSMutableArray *)dataArray
{
    if (_dataArray==nil) {
        self.dataArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArray;
    
}

-(NSMutableArray *)dataArr
{
    if (_dataArr==nil) {
        self.dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}


-(NSString*)getUrlStr
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:60*60*8- 60*60*24*_day];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *str = [formatter stringFromDate:date];
    
    NSLog(@"数据日期---%@",str);
    
    NSString *url = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/feed?date=%@&num=1",str];
    return url;
}


-(void)geteData
{

    
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:[self getUrlStr] parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            if (responseObject!=nil) {

                
                for (NSDictionary *dic in responseObject[@"dailyList"])
                {
                    for (NSDictionary *dict in dic[@"videoList"])
                    {
                        ILDailySelectModel *model = [[ILDailySelectModel alloc]init];
                        [model setValuesForKeysWithDictionary:dict];
                        [self.dataArr addObject:model];
           
                        //删除之前数据
                        [_dataBase executeUpdate:@"DELETE FROM ILVideo"];
                        //插入到数据库
                [_dataBase executeUpdate:@"INSERT INTO ILVideo (coverForDetail, title, duration, category) VALUES (?,?,?,?)",model.coverForDetail,model.title,[NSNumber numberWithInt:model.duration],model.category];
                    }
                }
                NSLog(@"==%lu",(unsigned long)self.dataArr.count);
           
                [self.tableView.footer endRefreshing];
                [self.tableView reloadData];
            }else{
#pragma 当解析不出数据时  给数据库内数据
                self.dataArr =_dataArray;
            }
            
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            NSLog(@"error----%@",error);
        }];
}





- (void)viewDidLoad {
    [super viewDidLoad];
    self.day=0;
  
    self.tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
 
//设置Cell高度
    self.tableView.rowHeight = 777*SCREEN_WIDTH/1242;
    
      [self geteData];
//注册Cell
    [self.tableView registerClass:[ILDailySelectTableViewCell class] forCellReuseIdentifier:@"dailySelect"];

    
    
///**************************************************数据持久化
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"ILive.db"];

    _dataBase = [FMDatabase databaseWithPath:filePath];

    if ([_dataBase open]) {
        NSLog(@"数据库打开成功");
        [_dataBase executeUpdate:@"CREATE TABLE ILVideo (coverForDetail text,  title text, duration integer, category text)"];
    } else {
        NSLog(@"数据库打开失败");
    }

    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM ILVideo"];

    while ([resultSet next]) {
        NSString *coverForDetail = [resultSet stringForColumn:@"coverForDetail"];
        NSString *category = [resultSet stringForColumn:@"category"];
        NSString *title = [resultSet stringForColumn:@"title"];
        NSInteger duration = [resultSet intForColumn:@"duration"];
    
       ILDailySelectModel *model = [[ILDailySelectModel alloc] init];
        model.coverForDetail = coverForDetail;
        model.title = title;
        model.category = category;
        model.duration = duration;
        [self.dataArray addObject:model];
    }
    [resultSet close];

    
    

    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(pastData)];
    [self.tableView.footer beginRefreshing];

}
-(void)pastData
{
   _day++;
    [self geteData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
      return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
    return self.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    ILDailySelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dailySelect" forIndexPath:indexPath];
    ILDailySelectModel *model = self.dataArr[indexPath.row];

#pragma 关闭选中cell效果
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dailySelectModel = model;
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ILDailySelectDetailViewController *dailySelectDVC = [[ILDailySelectDetailViewController alloc]init];
    
    //每次传的数据
    dailySelectDVC.dataArr = self.dataArr;
    dailySelectDVC.index = indexPath.row;

    
//#pragma 动画
    [UIView beginAnimations:nil context:NULL];
    [UIView  setAnimationDuration:0.7];
    [self.nav pushViewController:dailySelectDVC animated:YES];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.nav.view cache:NO];
    [UIView commitAnimations];
    
}






/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
